package com.jiuzhi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.util.ArrayList;
import java.util.List;

/**
 * 这是springbean的根配置，这个配置与spring mvc没有关系
 * 原来的spring项目中的springContext.xml配置文件
 * 在spring boot模式下，此类必须放在与ProprietorManagerApplication同包下才可，否则不生效
 * Created by moloch on 2017/8/31.
 */
@Configuration
@ComponentScan(basePackages = {"com.jiuzhi"},
        includeFilters = {@ComponentScan.Filter(
                type = FilterType.REGEX,
                pattern = {
                        "com.jiuzhi.*.service.*.*Service*",
                        "com.jiuzhi.*.dao.impl.*DaoImpl"
                }
        )}
)
public class RootConfig {

    private static Logger logger = LoggerFactory.getLogger(RootConfig.class);

    public static final String SPRING_CONFIG_LOCATION = "spring.config.location";

    /**
     * 自定义配置加载，方法定义为static的，保证优先加载
     * @return
     */
    @Bean
    public static PropertyPlaceholderConfigurer properties() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setIgnoreResourceNotFound(true);
        final List<Resource> resourceLst = new ArrayList<Resource>();


        if(System.getProperty(SPRING_CONFIG_LOCATION) != null){

            String configFilePath = System.getProperty(SPRING_CONFIG_LOCATION);
            String[] configFiles = configFilePath.split(",|;");

            FileSystemResource res =null;
            for (String configFile : configFiles) {
                if (configFile.startsWith("file:")){
                    resourceLst.add(new FileSystemResource(configFile));
                }else {
                    resourceLst.add( new ClassPathResource(configFile));
                }
            }
        }else {
            logger.info("读取");
            resourceLst.add(new ClassPathResource("config/application.properties"));
        }
        ppc.setLocations(resourceLst.toArray(new Resource[]{}));
        return ppc;
    }

}
